package com.ccsoft.annoreflect.utils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author chanchaw
 * @create 2022-09-24 10:56
 */
public class ReflectUtils {
    // 通过反射获取对象指定属性的值
    public static Object getFieldValue(Object obj, Field field) {
        Class<?> clazz = obj.getClass();
        String getterMethodName = getGetterMethodName(obj,field);
        Method getterMethod = null;
        try {
            getterMethod = clazz.getMethod(getterMethodName);
        } catch (NoSuchMethodException e) {
            return null;
        }

        Object ret = null;
        try {
            ret = getterMethod.invoke(obj);
        } catch (IllegalAccessException e) {
            return null;
        } catch (InvocationTargetException e) {
            return null;
        }
        return ret;
    }

    // 获取对象指定属性的 getter 方法名称
    // 遵循小驼峰模式
    public static String getGetterMethodName(Object obj,Field field){
        String fieldName = field.getName();
        return "get" + fieldName.substring(0,1).toUpperCase() + fieldName.substring(1);
    }

    public static String getSetterMethodName(Field field){
        return "set" + field.getName().substring(0,1).toUpperCase() + field.getName().substring(1);
    }
}
